package com.annhoa.security.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.annhoa.security.http.JwtAuthenticationResponse;
import com.annhoa.security.service.AuthService;
import com.annhoa.system.domain.User;
import com.annhoa.util.StringUtil;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * @author annhoa ajax 登录
 *
 */
@RestController // 此处Rest注解无法跳转html 需要@Controller :@ResponseBody和@Controller的合集
public class AuthController {
	@Value("${jwt.header}")
	private String tokenHeader;

	@Autowired
	private AuthService authService;
	/**
	 * POST登录
	 * @param username
	 * @param password
	 * @return
	 * @throws AuthenticationException
	 */
	@PostMapping(value = "/auth/login")
	public ResponseEntity<?> createAuthenticationToken(
			/// @RequestParam(value = "username", required = true)
			String username,
			/// @RequestParam(value = "password", required = true)
			String password) throws AuthenticationException {
		
		final String token = authService.login(username, password);
		// Return the token
		return ResponseEntity.ok(new JwtAuthenticationResponse(token));
	}
	
	/**
	 * get登录
	 * @param request
	 * @return
	 * @throws AuthenticationException
	 */
	@GetMapping(value = "/auth/refresh")
	public ResponseEntity<?> refreshAndGetAuthenticationToken(HttpServletRequest request)
			throws AuthenticationException {
		String token = request.getHeader(tokenHeader);

		if (StringUtil.isEmpty(token)) {
			return ResponseEntity.badRequest().body(null);
		}
		String refreshedToken = authService.refresh(token);
		if (refreshedToken == null) {
			return ResponseEntity.badRequest().body(null);
		} else {
			return ResponseEntity.ok(new JwtAuthenticationResponse(refreshedToken));
		}
	}

	@RequestMapping(value = "${jwt.route.authentication.register}", method = RequestMethod.POST)
	public User register(@RequestBody User addedUser) throws AuthenticationException {
		return authService.register(addedUser);
	}
}
